// 为了尽量的让浏览器识别一下我这边尽我所能的写了es5
// 存储端口
const portList = []
// 存下来wsUrl用来重新连接使用
let websocketUrl = 'ws://127.0.0.1:3000'
// ws实例
let websocket = null
// 当前错误次数
let webSocketError = 0
// 重连最大次数
const webSocketErrorMax = 6
// 我这边长连接保持使用的是计时器没有使用延时器 主要原因是后端不想跟我通心跳。。。。
let timeout = null
// 计时器发送时间
const delay = 30000
// 连接端  每次创建也就是new SharedWorker 都会调用onconnect
onconnect = function (e) {
  console.log(e)
  const port = e.ports[0]
  // 存储端口
  portList.push(port)
  // 监听port推送
  port.addEventListener('message', function (e) {
    // 取数据
    const data = e.data || {}
    const type = data.type
    const message = data.message
    console.log(type, message)
    switch (type) {
      case 'connect':
        // 创建websocket
        initSocket(message)
        break
      case 'close':
        // 关闭当前端口（new SharedWorker 会默认开启端口）
        if (portList.indexOf(port) > -1) {
          portList.splice(portList.indexOf(port), 1)
        } else {
          // 关闭websocket
          websocket.send('close')
          websocketClose()
          websocket = null
          // 关闭SharedWorker 通过self调用 SharedWorkerGlobalScope 的实例
          self.close()
        }
        break
      case 'message':
        // 发送websocket消息
        websocket.send(message)
        break
      default:
        break
    }
  })
  port.start()
}
// websocket创建
var initSocket = function (url) {
  if (websocket === null && url) {
    websocket = new WebSocket(url) // WebSocket服务端地址
    websocketUrl = url
  }
  websocket.onopen = function (event) {
    for (let i = 0; i < portList.length; i++) {
      const eElement = portList[i]
      eElement.postMessage(event.data)
    }
    webSocketError = 0
    heartCheck()
  }
  websocket.onmessage = function (event) {
    for (let i = 0; i < portList.length; i++) {
      const eElement = portList[i]
      eElement.postMessage(event.data)
    }
    // item!=port&&item.postMessage(workerResult);  /**不发给自己 */
  }
  websocket.onclose = function () {
    if (webSocketError < webSocketErrorMax) {
      websocket = null
      setTimeout(function () {
        initSocket(websocketUrl)
      }, 5000)
    } else {
      console.warn('已达到最大重连次数，取消重连')
      clearInterval(timeout)
    }
  }
  websocket.onerror = function (e) {
    webSocketError++
  }
}
// 心跳
function heartCheck() {
  timeout = setInterval(function () {
    websocket.send('heart')
  }, delay)
}
// websocket关闭
function websocketClose() {
  websocket.send('close')
  webSocketError = 33
  clearInterval(timeout)
  websocket.close()
}
